//
//  EbookNetRequest.m
//  ebook
//
//  Created by 吴超飞 on 16/2/23.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "EbookNetRequest.h"
#import <CommonCrypto/CommonHMAC.h>//CC_MD5
#import "GuestLoginManager.h"
#import <AdSupport/ASIdentifierManager.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#import "AFNetworkActivityIndicatorManager.h"
#import "AESenAndDe.h"

#define kTimeOut 6.0

@implementation EbookNetRequest

//解密解密的接口数据为字典
+(NSDictionary *)decryResponse:(id)response{
    
    if ([response isKindOfClass:[NSData class]]) {
        response = [[NSString alloc]initWithData:response encoding:NSUTF8StringEncoding];
    }
    
    if ([response isKindOfClass:[NSString class]]) {//若加密的结果为base64之后的字符串，则解密
      
        NSString *plainText = [AESenAndDe De_Base64andAESDeToString:response];
        
        return [plainText JSONValue];
    }
    return response;
}

//获取设备类型
+(NSString *)getDeviceType{
    NSString* deviceName = [[UIDevice currentDevice] systemName];
    NSString* phoneModel = [[UIDevice currentDevice] model];
    return deviceName;
}
/*
//GET 获取数据流并解密
+(void)dataTaskWithUrl:(NSString *)url success:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock{
    
    if([url rangeOfString:@"unencry"].length>0){//未加密，直接用get请求
        [self getUrl:url success:successBlock failed:failedBlock];
        return;
    }
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            [EbookNetRequest failNSURLSessionDataTask:nil error:error failedOperation:failedBlock];
        } else {
            NSDictionary *dict = [EncryptData decryptData:responseObject];
            NSString *err = [dict objectForKey:@"err"];
            NSString *result;
            MTLog(@"responseObject:%@",err);
            if ([err intValue] == 0) {//获取成功
                result = @"成功";
                successBlock(0,result,dict);
            }else{
                failedBlock([err intValue],[NSString stringWithFormat:@"错误码:%d",[err intValue]]);
            }
        }
    }];
    [dataTask resume];
}

//GET普通请求（未加密时调用）
+(void)getUrl:(NSString *)url success:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress)
     {}success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         
         if([url rangeOfString:@"unencry"].length==0){//加密数据，先解密
             responseObject = [EncryptData decryptData:responseObject];
         }
         
         NSString *err = [responseObject objectForKey:@"err"];
         NSString *result;
         MTLog(@"picdown responseObject:%@",err);
         if ([err intValue] == 0) {
             result = @"get请求成功";
             successBlock(0,result,responseObject);
         }else{
             result = [responseObject objectForKey:@"errmsg"];
             failedBlock([err intValue],result);
         }
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         [EbookNetRequest failNSURLSessionDataTask:nil error:error failedOperation:failedBlock];
     }];
}*/

+(AFHTTPSessionManager *)httpManager{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //    AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey];
    //    policy.validatesDomainName = YES;
    //    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    //    manager.securityPolicy = policy;
    //    manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    
    return manager;
}

+ (NSURLSessionDownloadTask *)downloadFileWithURLString:(NSString *)URLString
                                   downloadFileProgress:(void(^)(NSProgress *downloadProgress))downloadFileProgress
                                             saveToPath:(NSString *)saveToPath
                              downloadCompletionHandler:(void (^)(NSURL *filePath, NSError *error))downloadCompletionHandler
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString] cachePolicy:1 timeoutInterval:60];
    
    //保存文件的沙盒路径
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:saveToPath]) {
        [fm createDirectoryAtPath:saveToPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    manager.requestSerializer.HTTPShouldHandleCookies = YES;
    manager.requestSerializer  = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager.requestSerializer setTimeoutInterval:15];
    //把版本号信息传导请求头中
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"iOS-%@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]] forHTTPHeaderField:@"MM-Version"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept" ];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json",@"text/html", @"text/plain",nil];
    
    NSURLSessionDownloadTask *dataTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        if(downloadFileProgress)downloadFileProgress(downloadProgress);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        NSURL *downloadURL = [NSURL fileURLWithPath:saveToPath];
        NSURL *fileURL = [downloadURL URLByAppendingPathComponent:response.suggestedFilename];
        
        NSError *error;//原来存在该文件，则删除原来的，覆盖为新的文件
        NSString *path = [saveToPath stringByAppendingPathComponent:response.suggestedFilename];
        if([fm fileExistsAtPath:path])
            [fm removeItemAtPath:path error:&error];
        
        return fileURL;
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        if([error code] == NSURLErrorCancelled)return ;
        if(downloadCompletionHandler)downloadCompletionHandler(filePath,error);
        
    }];
    
    [dataTask resume];
    
    return dataTask;
}

+(void)loginWithName:(NSString *) userName passsword:(NSString *) password success:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock{
    
    if(!userName||!password)return;
    NSString *urlStr = [NSString stringWithFormat:@"%@/v1/user.html?act=login",kHost];
    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"application/json", @"text/json",@"text/html", nil];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//[AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = kTimeOut;
    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFormData:[userName dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"account"];
        [formData appendPartWithFormData:[password dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"password"];
        NSString *clientId = [[NSUserDefaults standardUserDefaults] objectForKey:KPushClientId];
        clientId = !clientId?@"":clientId;
        [formData appendPartWithFormData:[clientId dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"pushId"];
        [formData appendPartWithFormData:[kBundleStr dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"package"];
        [formData appendPartWithFormData:[APP_VERSION dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"version"];
        
        NSDictionary *signDict = @{@"account":userName,@"password":password,@"pushId":clientId,@"version":APP_VERSION,@"package":kBundleStr};
        [formData appendPartWithFormData:[[EbookNetRequest getSign:signDict] dataUsingEncoding:NSUTF8StringEncoding] name:@"sign"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        responseObject = [EbookNetRequest decryResponse:responseObject];
        if(kIsShowResponse)MTLog(@"login responseObject:%@",responseObject);
        NSString *result;
        if (responseObject && [responseObject[@"code"] intValue] == 0) {//获取成功
            result = @"登录成功";
            successBlock(0,result,responseObject);
        }else{
            result = [responseObject objectForKey:@"message"];
            if(!result||result.length==0)result=[NSString stringWithFormat:@"code:%@",responseObject[@"code"]];
            failedBlock([responseObject[@"code"] intValue],result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EbookNetRequest failNSURLSessionDataTask:task error:error failedOperation:failedBlock];
    }];
}

+(void)logoutSuccess:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock{
    
    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json",@"text/html", @"text/plain",nil];
    NSString *url = [NSString stringWithFormat:@"%@/app/user_api.php?act=logout",kHost];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    }success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        MTLog(@"注销成功！");
    }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull   error) {
        [EbookNetRequest failNSURLSessionDataTask:task error:error failedOperation:failedBlock];
    }];
}

+(void)registerWithName:(NSString *) userName passsword:(NSString *) password success:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock{
    
    if(!userName||!password)return;
    NSString *urlStr = [NSString stringWithFormat:@"%@/v1/user.html?act=register",kHost];
    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"application/json", @"text/json",@"text/html", nil];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = kTimeOut;
    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)  {
        
        [formData appendPartWithFormData:[userName dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"account"];
        [formData appendPartWithFormData:[password dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"password"];
        NSString *clientId = [[NSUserDefaults standardUserDefaults] objectForKey:KPushClientId];
        clientId = !clientId?@"":clientId;
        [formData appendPartWithFormData:[clientId dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"pushId"];
        NSString *deviceType = [EbookNetRequest getDeviceType];
        NSString *osVersion = [[UIDevice currentDevice] systemVersion];//手机系统版本
        [formData appendPartWithFormData:[deviceType dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"deviceType"];
        [formData appendPartWithFormData:[osVersion dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"clientOs"];
        [formData appendPartWithFormData:[kBundleStr dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"package"];
        [formData appendPartWithFormData:[APP_VERSION dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"version"];
        NSDictionary *signDict = @{@"account":userName,@"password":password,@"deviceType":deviceType,@"clientOs":osVersion,@"pushId":clientId,@"version":APP_VERSION,@"package":kBundleStr};
        [formData appendPartWithFormData:[[EbookNetRequest getSign:signDict] dataUsingEncoding:NSUTF8StringEncoding] name:@"sign"];
    }  progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        responseObject = [EbookNetRequest decryResponse:responseObject];
        if(kIsShowResponse)MTLog(@"register responseObject:%@",responseObject);
        NSString *result;
        NSString *err = responseObject[@"code"];
        if (err && [err integerValue] == 0) {//获取成功
            result = @"注册成功";
            successBlock(0,result,responseObject);
        }else{
            result = responseObject[@"message"];
            if(!result||result.length==0)result=[NSString stringWithFormat:@"code:%@",err];
            failedBlock([err intValue],result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EbookNetRequest failNSURLSessionDataTask:task error:error failedOperation:failedBlock];
    }];
}

//绑定账号
+(void)blindCurentGuestWithName:(NSString *) userName passsword:(NSString *) password success:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock{
    
    if(!userName||!password)return;
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:kToken];
    NSString *urlStr = [NSString stringWithFormat:@"%@/v1/user.html?act=accountBind",kHost];
    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"application/json", @"text/json",@"text/html", nil];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = kTimeOut;
    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
        
        [formData appendPartWithFormData:[userName dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"account"];
        [formData appendPartWithFormData:[token dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"token"];
        [formData appendPartWithFormData:[password dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"password"];
        NSString *clientId = [[NSUserDefaults standardUserDefaults] objectForKey:KPushClientId];
        clientId = !clientId?@"":clientId;
        [formData appendPartWithFormData:[clientId dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"pushId"];
        NSString *deviceType = [EbookNetRequest getDeviceType];
        NSString *osVersion = [[UIDevice currentDevice] systemVersion];//手机系统版本
        [formData appendPartWithFormData:[deviceType dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"deviceType"];
        [formData appendPartWithFormData:[osVersion dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"clientOs"];
        [formData appendPartWithFormData:[kBundleStr dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"package"];
        [formData appendPartWithFormData:[APP_VERSION dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"version"];
        NSDictionary *signDict = @{@"account":userName,@"token":token,@"password":password,@"deviceType":deviceType,@"clientOs":osVersion,@"pushId":clientId,@"version":APP_VERSION,@"package":kBundleStr};
        [formData appendPartWithFormData:[[EbookNetRequest getSign:signDict] dataUsingEncoding:NSUTF8StringEncoding] name:@"sign"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        responseObject = [EbookNetRequest decryResponse:responseObject];
        if(kIsShowResponse)MTLog(@"accbind responseObject:%@",responseObject);
        NSString *result;
        NSString *err = responseObject[@"code"];
        if ([err integerValue] == 0) {//获取成功
            result = @"绑定成功";
            successBlock(0,result,responseObject);
        }else{
            result = responseObject[@"message"];
            if(!result||result.length==0)result=[NSString stringWithFormat:@"code:%@",err];
            failedBlock([err intValue],result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EbookNetRequest failNSURLSessionDataTask:task error:error failedOperation:failedBlock];
    }];
}

//游客登录
+(void)guestLoginWithName:(NSString *) udid success:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock{
    
    if(!udid)return;
    NSString *urlStr = [NSString stringWithFormat:@"%@/v1/user.html?act=guest",kHost];
    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain",@"application/json", @"text/json",nil];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];//返回的是加密后的字符串，非json了
    manager.requestSerializer.timeoutInterval = kTimeOut;
    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSString *deviceType = [EbookNetRequest getDeviceType];
        NSString *osVersion = [[UIDevice currentDevice] systemVersion];//手机系统版本
        NSString *clientId = [[NSUserDefaults standardUserDefaults] objectForKey:KPushClientId];
        clientId = !clientId?@"":clientId;
        [formData appendPartWithFormData:[clientId dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"pushId"];
        [formData appendPartWithFormData:[udid dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"udid"];
        [formData appendPartWithFormData:[deviceType dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"deviceType"];
        [formData appendPartWithFormData:[osVersion dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"clientOs"];
        [formData appendPartWithFormData:[kBundleStr dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"package"];
        [formData appendPartWithFormData:[APP_VERSION dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"version"];
        NSDictionary *signDict = @{@"udid":udid,@"pushId":clientId,@"deviceType":deviceType,@"clientOs":osVersion,@"version":APP_VERSION,@"package":kBundleStr};
        [formData appendPartWithFormData:[[EbookNetRequest getSign:signDict] dataUsingEncoding:NSUTF8StringEncoding] name:@"sign"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //        responseObject = [EbookNetRequest decryResponse:responseObject];
        if(kIsShowResponse)MTLog(@"guest responseObject:%@",responseObject);
        NSString *result;
        NSString *err = responseObject[@"code"];
        if (err &&[err integerValue] == 0) {//成功
            result = @"游客登录成功";
            successBlock(0,result,responseObject);
        }else{
            result = responseObject[@"message"];
            if(!result||result.length==0)result=[NSString stringWithFormat:@"code:%@",err];
            failedBlock([err intValue],result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EbookNetRequest failNSURLSessionDataTask:task error:error failedOperation:failedBlock];
    }];
}

+(void)bookcaseSuccess:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock{
    
    NSString *urlStr = [NSString stringWithFormat:@"%@/v1/book.html?act=getbookcase",kHost];//,[[NSUserDefaults standardUserDefaults] objectForKey:kToken],arc4random()%100,kBundleStr,APP_VERSION
    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain",@"application/json", @"text/json",nil];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];//返回的是加密后的字符串，非json了
    manager.requestSerializer.timeoutInterval = kTimeOut;
    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSString *random = [NSString stringWithFormat:@"%d",arc4random()%100];
        NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:kToken];
        [formData appendPartWithFormData:[random dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"random"];
        [formData appendPartWithFormData:[token dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"token"];
        [formData appendPartWithFormData:[kBundleStr dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"package"];
        [formData appendPartWithFormData:[APP_VERSION dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"version"];
        NSDictionary *signDict = @{@"random":random,@"token":token,@"version":APP_VERSION,@"package":kBundleStr};
        [formData appendPartWithFormData:[[EbookNetRequest getSign:signDict] dataUsingEncoding:NSUTF8StringEncoding] name:@"sign"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        responseObject = [EbookNetRequest decryResponse:responseObject];
        NSString *err = responseObject[@"code"];
        NSString *result;
        if(kIsShowResponse)MTLog(@"bookcase responseObject:%@",responseObject);
        if (responseObject && [err intValue] == 0) {//获取成功
            result = @"获取书架列表成功";
            successBlock(0,result,responseObject);
        }else{
            result = [responseObject objectForKey:@"message"];
            failedBlock([err intValue],result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EbookNetRequest failNSURLSessionDataTask:task error:error failedOperation:failedBlock];
    }];
}

//书架推荐
+(void)recommendSuccess:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock{
    
    NSString *url = [NSString stringWithFormat:@"%@/app/book_api.php?act=recommend&package=%@&version=%@",kHost,kBundleStr,APP_VERSION];
    MTLog(@"recommend url:%@",url);
    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"application/json", @"text/json",@"text/html", nil];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    }success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        responseObject = [EbookNetRequest decryResponse:responseObject];
        NSString *err = [responseObject objectForKey:@"code"];
        NSString *result;
        if(kIsShowResponse)MTLog(@"recommendSuccess responseObject:%@",responseObject);
        if (responseObject && [err intValue] == 0) {//获取成功
            result = @"获取推荐列表成功";
            successBlock(0,result,responseObject);
        }else{
            result = responseObject[@"message"];
            failedBlock([err intValue],result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EbookNetRequest failNSURLSessionDataTask:task error:error failedOperation:failedBlock];
    }];
}

//添加书架
+(void)addBookcase:(NSString *) bookid success:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock{
    
    if(!bookid)return;
    NSString *urlStr = [NSString stringWithFormat:@"%@/v1/book.html?act=bookcaseadd",kHost];
    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"application/json", @"text/json",@"text/html", nil];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
        
        NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:kToken];
        [formData appendPartWithFormData:[[NSString stringWithFormat:@"%@", bookid] dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"aid"];
        [formData appendPartWithFormData:[token dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"token"];
        NSDictionary *signDict = @{@"aid":bookid,@"token":token};
        [formData appendPartWithFormData:[[EbookNetRequest getSign:signDict] dataUsingEncoding:NSUTF8StringEncoding] name:@"sign"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //        responseObject = [EbookNetRequest decryResponse:responseObject];//该接口没有做加密，服务端js也需要使用，所以未加密
        if(kIsShowResponse)MTLog(@"addBookcase responseObject:%@",responseObject);
        NSString *result;
        NSInteger err = [responseObject[@"code"] integerValue];
        if (responseObject && (err == 0 || err == 10)) {//获取成功
            result = @"添加书架成功";
            successBlock(0,result,responseObject);
        }else{
            result = [responseObject objectForKey:@"message"];
            failedBlock([[responseObject objectForKey:@"code"] intValue],result);
        }
    }  failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EbookNetRequest failNSURLSessionDataTask:task error:error failedOperation:failedBlock];
    }];
}

//移除书架
+(void)removeBookcase:(NSString *) bookid success:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock{
    
    if(!bookid)return;
    NSString *urlStr = [NSString stringWithFormat:@"%@/v1/book.html?act=bookcasedel",kHost];
    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"application/json", @"text/json",@"text/html", nil];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
        
        NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:kToken];
        [formData appendPartWithFormData:[[NSString stringWithFormat:@"%@", bookid] dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"aid"];
        [formData appendPartWithFormData:[token dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"token"];
        NSDictionary *signDict = @{@"aid":bookid,@"token":token};
        [formData appendPartWithFormData:[[EbookNetRequest getSign:signDict] dataUsingEncoding:NSUTF8StringEncoding] name:@"sign"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //        responseObject = [EbookNetRequest decryResponse:responseObject];
        if(kIsShowResponse)MTLog(@"removeBookcase responseObject:%@",responseObject);
        NSString *result;
        if (responseObject && [responseObject[@"code"] integerValue] == 0) {//获取成功
            result = @"移除书架成功";
            successBlock(0,result,responseObject);
        }else{
            result = responseObject[@"message"];
            failedBlock([responseObject[@"code"] intValue],result);
        }
    }  failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EbookNetRequest failNSURLSessionDataTask:task error:error failedOperation:failedBlock];
    }];
}

//获取书城菜单
+(void)getStoreMenuSuccess:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock{
    
    NSString *urlStr = [NSString stringWithFormat:@"%@/v1/book.html?act=menu",kHost];
    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"application/json", @"text/json",@"text/html", nil];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//[AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = kTimeOut;
    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFormData:[@"iOS" dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"platform"];
        [formData appendPartWithFormData:[kBundleStr dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"package"];
        [formData appendPartWithFormData:[APP_VERSION dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"version"];
        NSDictionary *signDict = @{@"platform":@"iOS",@"version":APP_VERSION,@"package":kBundleStr};
        [formData appendPartWithFormData:[[EbookNetRequest getSign:signDict] dataUsingEncoding:NSUTF8StringEncoding] name:@"sign"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        responseObject = [EbookNetRequest decryResponse:responseObject];
        if(kIsShowResponse)MTLog(@"getStoreMenu responseObject:%@",responseObject);
        NSString *err = responseObject[@"code"];
        NSString *result;
        if (responseObject && [err intValue] == 0) {//获取成功
            result = @"获取书城菜单成功";
            successBlock(0,result,responseObject);
        }else{
            result = responseObject[@"message"];
            failedBlock([err intValue],result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EbookNetRequest failNSURLSessionDataTask:task error:error failedOperation:failedBlock];
    }];
}

//章节报错
+(void)submitError:(NSString *)bookid chapterId:(NSString *) chapterId type:(NSInteger)type success:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock{
    
    if(!bookid||!chapterId)return;
    NSString *urlStr = [NSString stringWithFormat:@"%@/v1/book.html?act=usersubmiterror",kHost];
    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"application/json", @"text/json",@"text/html", nil];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//[AFHTTPResponseSerializer serializer];
    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
        
        NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:kToken];
        [formData appendPartWithFormData:[token dataUsingEncoding:NSUTF8StringEncoding] name:@"token"];
        [formData appendPartWithFormData:[bookid dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"articleId"];
        [formData appendPartWithFormData:[chapterId dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"chapterId"];
        [formData appendPartWithFormData:[[NSString stringWithFormat:@"%d",(int)type] dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"errorType"];
        
        NSDictionary *signDict = @{@"articleId":bookid,@"chapterId":chapterId,@"errorType":[NSString stringWithFormat:@"%d",(int)type],@"token":token};
        [formData appendPartWithFormData:[[EbookNetRequest getSign:signDict] dataUsingEncoding:NSUTF8StringEncoding] name:@"sign"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //        responseObject = [EbookNetRequest decryResponse:responseObject];
        if(kIsShowResponse)MTLog(@"submitError responseObject:%@",responseObject);
        NSString *result;
        if (responseObject && [responseObject[@"code"] integerValue] == 0) {//成功
            
            result = @"提交错误信息成功";
            successBlock(0,result,responseObject);
        }else{
            
            result = responseObject[@"message"];
            failedBlock([responseObject[@"code"] intValue],result);
        }
        
    }  failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EbookNetRequest failNSURLSessionDataTask:task error:error failedOperation:failedBlock];
    }];
}

//意见反馈
+(void)postFeedBackContent:(NSString *)content contact:(NSString *)contact Success:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock
{
    if(!contact||!content)return;
    NSString *urlStr = [NSString stringWithFormat:@"%@/v1/book.html?act=usersubmitsuggest", kHost];
    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"application/json", @"text/json",@"text/html", nil];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
        
        NSString *deviceType = [EbookNetRequest getDeviceType];
        NSString *osVersion = [[UIDevice currentDevice] systemVersion];//手机系统版本
        NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:kToken];
        [formData appendPartWithFormData:[content dataUsingEncoding:NSUTF8StringEncoding] name:@"content"];
        [formData appendPartWithFormData:[contact dataUsingEncoding:NSUTF8StringEncoding] name:@"email"];
        [formData appendPartWithFormData:[token dataUsingEncoding:NSUTF8StringEncoding] name:@"token"];
        [formData appendPartWithFormData:[deviceType dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"deviceType"];
        [formData appendPartWithFormData:[osVersion dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"clientOs"];
        [formData appendPartWithFormData:[kBundleStr dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"package"];
        [formData appendPartWithFormData:[APP_VERSION dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"version"];
        NSDictionary *signDict = @{@"content":content,@"email":contact,@"deviceType":deviceType,@"clientOs":osVersion,@"version":APP_VERSION,@"package":kBundleStr,@"token":token};
        [formData appendPartWithFormData:[[EbookNetRequest getSign:signDict] dataUsingEncoding:NSUTF8StringEncoding] name:@"sign"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        responseObject = [EbookNetRequest decryResponse:responseObject];
        if(kIsShowResponse)MTLog(@"postFeedBackContent responseObject:%@",responseObject);
        if (responseObject && 0 == [responseObject[@"code"] integerValue]) {
            successBlock(0, responseObject[@"message"], responseObject);
        } else {
            failedBlock(1, responseObject[@"message"]);
        }
    }  failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EbookNetRequest failNSURLSessionDataTask:task error:error failedOperation:failedBlock];
    }];
}

+(void)failNSURLSessionDataTask:(NSURLSessionDataTask *)task error:(NSError *)error failedOperation:(RequestFailed)failedBlock{
    
    MTLog(@"AFHTTPRequestOperation发生错误！%@",error);
    
    NSString *errorString = [error.userInfo objectForKey:@"NSLocalizedDescription"];
    if(error.code== NSURLErrorBadServerResponse)
        errorString=@"对不起，系统异常，请稍后再试";
    failedBlock(-999,errorString);
}

+ (void)downloadFontListSuccess:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock {
    
    NSString *url = [NSString stringWithFormat:@"%@/v1/book.html?act=fontlist",kHost];
    MTLog(@"downloadFont url:%@",url);
    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"application/json", @"text/json",@"text/html", nil];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
        
        [formData appendPartWithFormData:[kBundleStr dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"package"];
        [formData appendPartWithFormData:[APP_VERSION dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"version"];
        NSDictionary *signDict = @{@"version":APP_VERSION,@"package":kBundleStr};
        [formData appendPartWithFormData:[[EbookNetRequest getSign:signDict] dataUsingEncoding:NSUTF8StringEncoding] name:@"sign"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        responseObject = [EbookNetRequest decryResponse:responseObject];
        if(kIsShowResponse)MTLog(@"downloadFont responseObject:suc");
        NSString *err = [responseObject objectForKey:@"code"];
        NSString *result;
        if ([err intValue] == 0) {//获取成功
            result = @"获取字体成功";
            successBlock(0,result,responseObject);
        }else{
            result = responseObject[@"message"];
            failedBlock([err intValue],result);
        }
    }  failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EbookNetRequest failNSURLSessionDataTask:task error:error failedOperation:failedBlock];
    }];
}

+(void)changeSources:(NSString *)bookid success:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock {
    
    NSString *urlStr = [NSString stringWithFormat:@"%@/v1/book.html?act=source", kHost];
    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"application/json", @"text/json",@"text/html", nil];
    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
        
        [formData appendPartWithFormData:[bookid dataUsingEncoding:NSUTF8StringEncoding] name:@"aid"];
        
        NSDictionary *signDict = @{@"aid":bookid};
        [formData appendPartWithFormData:[[EbookNetRequest getSign:signDict] dataUsingEncoding:NSUTF8StringEncoding] name:@"sign"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    }success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //        responseObject = [EbookNetRequest decryResponse:responseObject];
        if(kIsShowResponse)MTLog(@"getchangeSources responseObject:suc");
        NSString *err = responseObject[@"code"];
        NSString *result;
        if (responseObject && [err intValue] == 0) {//获取成功
            result = @"换源接口获取成功";
            successBlock(0,result,responseObject);
        }else{
            result = responseObject[@"message"];
            failedBlock([err intValue],result);
        }
        
    }  failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EbookNetRequest failNSURLSessionDataTask:task error:error failedOperation:failedBlock];
    }];
}

//解锁
+(void)unlock:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock{
    
    NSString *url = [NSString stringWithFormat:@"%@/app/user_api.php?act=unlock&package=%@&version=%@",kHost,kBundleStr,APP_VERSION];
    MTLog(@"unlock url:%@",url);
    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"application/json", @"text/json",@"text/html", nil];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    }success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        responseObject = [EbookNetRequest decryResponse:responseObject];
        if(kIsShowResponse) MTLog(@"unlock responseObject:%@",responseObject);
        NSString *err = [responseObject objectForKey:@"code"];
        NSString *result;
        if ([err intValue] == 0) {//获取成功
            result = @"解锁成功";
            successBlock(0,result,responseObject);
        }else{
            result = responseObject[@"message"];
            failedBlock([err intValue],result);
        }
    }  failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EbookNetRequest failNSURLSessionDataTask:task error:error failedOperation:failedBlock];
    }];
}

//检查更新
+(void)checkBookUpdate:(NSString *) bookid success:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock{
    
    if(!bookid)return;
    NSString *urlStr = [NSString stringWithFormat:@"%@/v1/book.html?act=showupdatetime",kHost];
    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"application/json", @"text/json",@"text/html", nil];
    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
        
        [formData appendPartWithFormData:[bookid dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"aid"];
        [formData appendPartWithFormData:[kBundleStr dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"package"];
        [formData appendPartWithFormData:[APP_VERSION dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"version"];
        NSDictionary *signDict = @{@"aid":bookid,@"package":kBundleStr,@"version":APP_VERSION};
        [formData appendPartWithFormData:[[EbookNetRequest getSign:signDict] dataUsingEncoding:NSUTF8StringEncoding] name:@"sign"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if(kIsShowResponse)MTLog(@"checkupdate responseObject:%@",responseObject);
        NSString *result;
        if (responseObject && [responseObject[@"code"] integerValue] == 0) {//获取成功
            result = @"获取时间成功";
            successBlock(0,result,responseObject);
        }else{
            result = responseObject[@"message"];
            failedBlock([responseObject[@"code"] intValue],result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EbookNetRequest failNSURLSessionDataTask:task error:error failedOperation:failedBlock];
    }];
}

//app版本数据获取
+(void)applicationGetVersionDataSuccess:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock {
    
    NSString *url = [NSString stringWithFormat:@"%@/v1/book.html?act=checkversion",kHost];
    MTLog(@"version url:%@",url);
    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"application/json", @"text/json",@"text/html", nil];
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
        
        [formData appendPartWithFormData:[kBundleStr dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"package"];
        [formData appendPartWithFormData:[APP_VERSION dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"version"];
        [formData appendPartWithFormData:[@"iOS" dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"platform"];
        NSDictionary *signDict = @{@"platform":@"iOS",@"package":kBundleStr,@"version":APP_VERSION};
        [formData appendPartWithFormData:[[EbookNetRequest getSign:signDict] dataUsingEncoding:NSUTF8StringEncoding] name:@"sign"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if(kIsShowResponse)MTLog(@"version responseObject:%@",responseObject);
        successBlock(0,@"版本数据获取成功",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EbookNetRequest failNSURLSessionDataTask:task error:error failedOperation:failedBlock];
    }];
}

//搜索联想
+(void)searchText:(NSString *)stext resultSuccess:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock{
    
    NSString *url = [NSString stringWithFormat:@"%@/v1/book.html?act=search",kHost];
    MTLog(@"searchText url:%@",url);
    AFHTTPSessionManager *manager = [EbookNetRequest httpManager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain",@"application/json", @"text/json",nil];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];//返回的是加密后的字符串，非json了
    manager.requestSerializer.timeoutInterval = kTimeOut;
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:kToken];
        [formData appendPartWithFormData:[stext dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"word"];
        [formData appendPartWithFormData:[token dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"token"];
        [formData appendPartWithFormData:[@"1" dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"page"];
        [formData appendPartWithFormData:[@"1" dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"short"];
        [formData appendPartWithFormData:[kBundleStr dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"package"];
        [formData appendPartWithFormData:[APP_VERSION dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"version"];
        NSDictionary *signDict = @{@"word":stext,@"page":@"1",@"token":token,@"version":APP_VERSION,@"package":kBundleStr,@"short":@"1"};
        [formData appendPartWithFormData:[[EbookNetRequest getSign:signDict] dataUsingEncoding:NSUTF8StringEncoding] name:@"sign"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString *err = responseObject[@"code"];
        NSString *result;
        if(kIsShowResponse)MTLog(@"searchText responseObject:%@",responseObject);
        if (responseObject && [err intValue] == 0) {//获取成功
            result = @"获取搜索联想列表成功";
            successBlock(0,result,responseObject);
        }else{
            failedBlock([err intValue],@"搜索失败");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EbookNetRequest failNSURLSessionDataTask:task error:error failedOperation:failedBlock];
    }];
}

#pragma mark - MD5加密
+(NSString *)MD5:(NSString *)str
{
    if(!str)return @"";
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

//获取签名
+(NSString *)getSign:(NSDictionary *)dict{
    
    NSArray *keys = [dict allKeys];
    [keys sortedArrayUsingSelector:@selector(compare:)];
    NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES];
    NSArray *descriptors = [NSArray arrayWithObject:descriptor];
    NSArray *resultArray = [keys sortedArrayUsingDescriptors:descriptors];
    NSMutableString *signStr = [NSMutableString string];
    for (NSString *key in resultArray) {
        [signStr appendFormat:@"%@=%@&",key,[dict objectForKey:key]];
    }
    [signStr appendString:kPrivatekey];
    NSString *sign = [EbookNetRequest MD5:signStr];
    
    MTLog(@"signStr:%@,sign:%@",signStr,sign);
    
    return sign;
}

+ (NSString *)AD_UUID{
    
    NSString *uuid = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    if ([uuid isEqualToString:@"00000000-0000-0000-0000-000000000000"]) {
        uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    }
    return uuid;
}

//获得设备型号
+ (NSString *)getCurrentDeviceModel
{
    int mib[2];
    size_t len;
    char *machine;
    
    mib[0] = CTL_HW;
    mib[1] = HW_MACHINE;
    sysctl(mib, 2, NULL, &len, NULL, 0);
    machine = malloc(len);
    sysctl(mib, 2, machine, &len, NULL, 0);
    
    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    free(machine);
    
    if ([platform isEqualToString:@"iPhone1,1"])return @"iPhone 2G (A1203)";
    else if([platform isEqualToString:@"iPhone1,2"])return @"iPhone 3G (A1241/A1324)";
    else if([platform isEqualToString:@"iPhone2,1"])return @"iPhone 3GS (A1303/A1325)";
    else if([platform isEqualToString:@"iPhone3,1"])return @"iPhone 4 (A1332)";
    else if([platform isEqualToString:@"iPhone3,2"])return @"iPhone 4 (A1332)";
    else if([platform isEqualToString:@"iPhone3,3"])return @"iPhone 4 (A1349)";
    else if([platform isEqualToString:@"iPhone4,1"])return @"iPhone 4S (A1387/A1431)";
    else if([platform isEqualToString:@"iPhone5,1"])return @"iPhone 5 (A1428)";
    else if([platform isEqualToString:@"iPhone5,2"])return @"iPhone 5 (A1429/A1442)";
    else if([platform isEqualToString:@"iPhone5,3"])return @"iPhone 5c (A1456/A1532)";
    else if([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (A1507/A1516/A1526/A1529)";
    else if([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (A1453/A1533)";
    else if([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (A1457/A1518/A1528/A1530)";
    else if([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus (A1522/A1524)";
    else if([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6 (A1549/A1586)";
    else if([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
    else if([platform isEqualToString:@"iPhone9,1"]) return @"iPhone7";
    else if([platform isEqualToString:@"iPhone9,3"]) return @"iPhone7";
    else if([platform isEqualToString:@"iPhone9,2"]) return @"iPhone7Plus";
    else if([platform isEqualToString:@"iPhone9,4"]) return @"iPhone7Plus";
    else if([platform isEqualToString:@"iPhone10,1"])return@"iPhone 8";
    else if([platform isEqualToString:@"iPhone10,4"])return@"iPhone 8";
    else if([platform isEqualToString:@"iPhone10,2"]) return@"iPhone 8 Plus";
    else if([platform isEqualToString:@"iPhone10,5"]) return@"iPhone 8 Plus";
    else if([platform isEqualToString:@"iPhone10,3"]) return@"iPhone X";
    else if([platform isEqualToString:@"iPhone10,6"]) return@"iPhone X";
    else if([platform isEqualToString:@"iPhone11,8"]) return@"iPhone XR";
    else if([platform isEqualToString:@"iPhone11,2"]) return@"iPhone XS";
    else if([platform isEqualToString:@"iPhone11,6"]) return@"iPhone XS Max";
    
    else if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G (A1213)";
    else if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G (A1288)";
    else if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G (A1318)";
    else if ([platform isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G (A1367)";
    else if ([platform isEqualToString:@"iPod5,1"])   return @"iPod Touch 5G (A1421/A1509)";
    else if ([platform isEqualToString:@"iPod7,1"])   return @"iPod Touch 6G (A1574)";
    
    else if ([platform isEqualToString:@"iPad1,1"])   return @"iPad 1G (A1219/A1337)";
    else if ([platform isEqualToString:@"iPad2,1"])   return @"iPad 2 (A1395)";
    else if ([platform isEqualToString:@"iPad2,2"])   return @"iPad 2 (A1396)";
    else if ([platform isEqualToString:@"iPad2,3"])   return @"iPad 2 (A1397)";
    else if ([platform isEqualToString:@"iPad2,4"])   return @"iPad 2 (A1395+New Chip)";
    else if ([platform isEqualToString:@"iPad2,5"])   return @"iPad Mini 1G (A1432)";
    else if ([platform isEqualToString:@"iPad2,6"])   return @"iPad Mini 1G (A1454)";
    else if ([platform isEqualToString:@"iPad2,7"])   return @"iPad Mini 1G (A1455)";
    
    else if ([platform isEqualToString:@"iPad3,1"])   return @"iPad 3 (A1416)";
    else if ([platform isEqualToString:@"iPad3,2"])   return @"iPad 3 (A1403)";
    else if ([platform isEqualToString:@"iPad3,3"])   return @"iPad 3 (A1430)";
    else if ([platform isEqualToString:@"iPad3,4"])   return @"iPad 4 (A1458)";
    else if ([platform isEqualToString:@"iPad3,5"])   return @"iPad 4 (A1459)";
    else if ([platform isEqualToString:@"iPad3,6"])   return @"iPad 4 (A1460)";
    
    else if ([platform isEqualToString:@"iPad4,1"])   return @"iPad Air (A1474)";
    else if ([platform isEqualToString:@"iPad4,2"])   return @"iPad Air (A1475)";
    else if ([platform isEqualToString:@"iPad4,3"])   return @"iPad Air (A1476)";
    else if ([platform isEqualToString:@"iPad4,4"])   return @"iPad Mini 2G (A1489)";
    else if ([platform isEqualToString:@"iPad4,5"])   return @"iPad Mini 2G (A1490)";
    else if ([platform isEqualToString:@"iPad4,6"])   return @"iPad Mini 2G (A1491)";
    else if ([platform isEqualToString:@"iPad4,7"])   return @"iPad mini3";
    else if ([platform isEqualToString:@"iPad4,8"])   return @"iPad mini3";
    else if ([platform isEqualToString:@"iPad4,9"])   return @"iPad mini3";
    else if ([platform isEqualToString:@"iPad5,1"])   return @"iPad mini4";
    else if ([platform isEqualToString:@"iPad5,2"])   return @"iPad mini4";
    
    else if ([platform isEqualToString:@"iPad5,3"]) return@"iPad Air 2";
    else if ([platform isEqualToString:@"iPad5,4"])return@"iPad Air 2";
    else if ([platform isEqualToString:@"iPad6,3"]) return@"iPad Pro 9.7";
    else if ([platform isEqualToString:@"iPad6,4"]) return@"iPad Pro 9.7";
    else if ([platform isEqualToString:@"iPad6,7"]) return@"iPad Pro 12.9";
    else if ([platform isEqualToString:@"iPad6,8"]) return@"iPad Pro 12.9";
    else if ([platform isEqualToString:@"iPad6,11"]) return@"iPad 5";
    else if ([platform isEqualToString:@"iPad6,12"]) return@"iPad 5";
    else if ([platform isEqualToString:@"iPad7,1"]) return@"iPad Pro 12.9 2nd";
    else if ([platform isEqualToString:@"iPad7,2"]) return@"iPad Pro 12.9 2nd";
    else if ([platform isEqualToString:@"iPad7,4"]) return@"iPad Pro 10.5";
    else if ([platform isEqualToString:@"iPad7,5"]) return@"iPad 6";
    else if ([platform isEqualToString:@"iPad7,6"]) return@"iPad 6";
    else if ([platform isEqualToString:@"iPad8,1"]) return@"iPad Pro (11-inch)";
    else if ([platform isEqualToString:@"iPad8,2"]) return@"iPad Pro (11-inch)";
    else if ([platform isEqualToString:@"iPad8,3"]) return@"iPad Pro (11-inch)";
    else if ([platform isEqualToString:@"iPad8,4"]) return@"iPad Pro (11-inch)";
    
    else if ([platform isEqualToString:@"iPad8,5"]) return@"iPad Pro (12.9-inch) 3rd";
    else if ([platform isEqualToString:@"iPad8,6"]) return@"iPad Pro (12.9-inch) 3rd";
    else if ([platform isEqualToString:@"iPad8,7"]) return@"iPad Pro (12.9-inch) 3rd";
    else if ([platform isEqualToString:@"iPad8,8"]) return@"iPad Pro (12.9-inch) 3rd";
    
    else if ([platform isEqualToString:@"i386"]) return @"iPhone Simulator";
    else if ([platform isEqualToString:@"x86_64"]) return @"iPhone Simulator";
    
    return platform;
}

+(void)getBook:(NSString *)bookid success:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock {
    if(!bookid)return;
    NSString *urlStr = [NSString stringWithFormat:@"%@/app/book_api.php?act=book",kHost];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json",@"text/html", @"text/plain",nil];
    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFormData:[bookid dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"aid"];
        NSDictionary *signDict = @{@"aid":bookid};
        [formData appendPartWithFormData:[[EbookNetRequest getSign:signDict] dataUsingEncoding:NSUTF8StringEncoding] name:@"sign"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if(kIsShowResponse)MTLog(@"getBook responseObject:suc");
        NSString *result;
        if ([[responseObject objectForKey:@"code"] integerValue] == 0) {//获取成功
            result = @"获取Book内容成功";
            successBlock(0,result,responseObject);
        }else if ([[responseObject objectForKey:@"code"] integerValue] == 1) {//未登录
            [EbookNetRequest logoutSuccess:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
                [EbookNetRequest getBook:bookid success:^(int stateCode, NSString *successMsg, NSDictionary *dict) {} failed:^(int stateCode, NSString *failMsg) {}];
            } failed:^(int stateCode, NSString *failMsg) {}];
        }else{
            result = [responseObject objectForKey:@"message"];
            failedBlock([[responseObject objectForKey:@"code"] intValue],result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EbookNetRequest failNSURLSessionDataTask:task error:error failedOperation:failedBlock];
    }];
}
/*
 + (void)getNativeStoreWithPage:(NSInteger)page sort:(NSInteger)sort fullflag:(NSInteger)fullflag order:(NSString *)order success:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock {
 if (page==0) return;
 NSString *urlStr = [NSString stringWithFormat:@"http://bapp.applex.top:8070/api/v1/store/booklist?page=%ld&sort=%ld&fullflag=%ld&subsort=0&order=%@&package=%@&version=%@", page, sort, fullflag, order,kBundleStr,APP_VERSION];
 MTLog(@"getSeeklistWithSortId:%@", urlStr);
 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
 AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
 manager.responseSerializer = [AFHTTPResponseSerializer serializer];
 NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
 NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
 if (error) {
 [EbookNetRequest failNSURLSessionDataTask:dataTask error:error failedOperation:failedBlock];
 } else {
 NSDictionary *dict = [EncryptData decryptData:responseObject];
 NSString *err = [dict objectForKey:@"code"];
 NSString *result;
 if(kIsShowResponse)MTLog(@"responseObject:%@",err);
 if ([err intValue] == 0) {//获取成功
 result = @"成功";
 successBlock(0,result,dict);
 }else{
 failedBlock([err intValue],[NSString stringWithFormat:@"错误码:%d",[err intValue]]);
 }
 }
 }];
 [dataTask resume];
 }
 
 +(void)getSeekOptionsSuccess:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock {
 NSString *url = [NSString stringWithFormat:@"http://bapp.applex.top:8070/api/v1/store/booksorts?package=%@&version=%@",kBundleStr,APP_VERSION];
 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
 AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
 manager.responseSerializer = [AFHTTPResponseSerializer serializer];
 NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
 NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
 if (error) {
 [EbookNetRequest failNSURLSessionDataTask:dataTask error:error failedOperation:failedBlock];
 } else {
 NSDictionary *dict = [EncryptData decryptData:responseObject];
 NSString *err = [dict objectForKey:@"code"];
 NSString *result;
 if(kIsShowResponse)MTLog(@"responseObject:%@",err);
 if ([err intValue] == 0) {//获取成功
 result = @"成功";
 successBlock(0,result,dict);
 }else{
 failedBlock([err intValue],[NSString stringWithFormat:@"错误码:%d",[err intValue]]);
 }
 }
 }];
 [dataTask resume];
 }*/

@end
